package com.szf.task.service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.szf.base.exception.GenericException;
import com.szf.base.service.BaseService;
import com.szf.task.entity.Task;
import com.szf.task.entity.TaskResult;
import com.szf.util.MapUtil;
import com.szf.util.StringUtil;

@Service
public class TaskService extends BaseService {
	@Autowired
	private TaskManager taskManager;

	public Task findById(String taskId) {
		return hibernateDao.get(Task.class, taskId);
	}

	public void save(Task task) {
		String hql = "from Task t where t.appId = :appId";
		Map param = new HashMap();
		param.put("appId", task.getAppId());
		List list = super.hibernateDao.query(hql, param);
		if (list.size() > 0) {
			throw new GenericException("appId only can be used in a task!");
		}
		super.hibernateDao.saveOrUpdate(task);
		taskManager.addTask(task);
	}

	public void deleteTask(String ids) {
		if (StringUtil.isEmpty(ids)) {
			return;
		}
		String inIds = StringUtil.getInString(ids);
		Map<String, String> param = new HashMap<String, String>();
		param.put("ids", inIds);
		super.ibatisDao.delete("sinlog.deleteTask", param);
	}

	public void addTaskResult(TaskResult taskResult) {
		super.hibernateDao.saveOrUpdate(taskResult);
	}

	public void update(Task task) {
		super.hibernateDao.update(task);
	}

	public List<Map> queryUseAppInfo(String accountId) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("accountId", accountId);
		return super.ibatisDao.queryForList("sinlog.queryUseAppInfo", param);
	}

	public List<String> getResultWebId() {
		List<Map> list = super.ibatisDao.queryForList("sinlog.queryWebId");
		List<String> rs = new LinkedList<String>();
		for (Map m : list) {
			String webId = MapUtil.getMap(m, "webId");
			if (!StringUtil.isEmpty(webId)) {
				rs.add(webId);
			}
		}
		return rs;
	}
}
